﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace WebTranslator {
	public class MasterListenerTranslation : Protocol {
		CMSProtocolS master;
		TcpClient client;
		public MasterListenerTranslation(CMSProtocolS master) {
			this.master = master;
		}
		public bool IsConnected { private set; get; }
		public int port { private set; get; }
		public IPAddress Ip { get; private set; }
		public void Connect(IPAddress ip, int port) {
			IsConnected = false;
			this.port = port;
			TcpListener listener = new TcpListener(ip, port);
			listener.Start();
			listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptSocketCallback), listener);
		}

		private void DoAcceptSocketCallback(IAsyncResult ar) {
			client = (ar.AsyncState as TcpListener).EndAcceptTcpClient(ar);
			SetSockets(client.Client);
			string[] napisy = Receive().Split(' '); 
			if (napisy[0] == "TS") {
				Ip = IPAddress.Parse(napisy[1]);
				Send("OK");
				IsConnected = true;
			}
			new Thread(Listen).Start();
		}
		//funkcja do obsługi połączenia Serwera językowego z serwerem głównym
		public void Listen() {
			string msg;
			while (true) {
				msg = Receive();
				string[] napisy = msg.Split(' ');
				switch (napisy[0]) {
					case "ilemampkt":
						Send(napisy[1] + " " + Baza.IlePkt(napisy[1]) + "");
						break;
                    case "dodajpkt":
                        Baza.DodajPkt(napisy[1], napisy[2]);
                        Send(napisy[1] +' ' + Baza.IlePkt(napisy[1]));
                        break;
					case "users":
						CMSProtocolS.usersCount[port - StartingApplicationPorts.MainServerToTranslationServers] = int.Parse(napisy[1]);
						break;
					default:
						Send("Zły komunikat");
						break;
				}
			}
		}
	}
}
